import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../system/fontsize_provider.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:wms/utils/utils.dart';
import '../../services/api_service.dart';
import '../../services/auth_service.dart';
import '../../utils/message_box.dart';
import '../../utils/rangeInput_formatter.dart';

class InvAdjustmentDetailPage extends StatefulWidget {
  const InvAdjustmentDetailPage({super.key});

  @override
  State<InvAdjustmentDetailPage> createState() => _InventoryAdjustmentPageState();
}

class _InventoryAdjustmentPageState extends State<InvAdjustmentDetailPage> with WidgetsBindingObserver {
  // 输入控制器
  final TextEditingController _itemController = TextEditingController();
  final TextEditingController _locationController = TextEditingController();
  final TextEditingController _quantityController = TextEditingController();
  final TextEditingController _notesController = TextEditingController();

  // 焦点控制器
  final FocusNode _itemFocusNode = FocusNode(canRequestFocus: true);
  final FocusNode _locationFocusNode = FocusNode(canRequestFocus: true);
  final FocusNode _quantityFocusNode = FocusNode(canRequestFocus: true);
  final FocusNode _notesFocusNode = FocusNode(canRequestFocus: true);

  // 键盘状态管理（默认全部收起）
  bool _locationKeyboardVisible = false;
  bool _itemKeyboardVisible = false;
  bool _quantityKeyboardVisible = false;
  String? _currentFocusField;

  // 当前数量
  int? currentQuantity = 0;
  int? locationId;
  bool quantityOnly = false;
  late int maxAllowedValue = 9999999999999;

  late double _fontScale;
  bool isEmpty = false;

  late int? warehouseId;
  late String? packKey = '';
  late String itemNumber;
  late String? internalItemNumber = '';

  // 调整类型：替换原下拉框，用变量跟踪选中的按钮
  String? _selectedAdjustmentType;

  // 输入验证状态
  Map<String, String?> validationErrors = {};

  static const double _bottomButtonHeight = 80;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    
    // 初始化选中的调整类型为 "Increase"
    _selectedAdjustmentType = 'Increase';
    
    // 添加输入监听
    _itemController.addListener(() => _clearErrorOnInput('item'));
    _locationController.addListener(() => _clearErrorOnInput('location'));
    _quantityController.addListener(() => _clearErrorOnInput('quantity'));
    
    // 初始化焦点监听
    _initFocusListeners();
    
    // 初始聚焦Location，先隐藏键盘再聚焦
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      if (mounted) {
        await _hideKeyboard();
        _focusOnField('location', showKeyboard: false);
      }
    });
  }

  // 初始化焦点监听
  void _initFocusListeners() {
    _locationFocusNode.addListener(() {
      _handleFocusChange('location', _locationFocusNode);
      if (_locationFocusNode.hasFocus && !_locationKeyboardVisible) {
        _hideKeyboard();
      }
    });
    _itemFocusNode.addListener(() {
      _handleFocusChange('item', _itemFocusNode);
      if (_itemFocusNode.hasFocus && !_itemKeyboardVisible) {
        _hideKeyboard();
      }
    });
    _quantityFocusNode.addListener(() {
      _handleFocusChange('quantity', _quantityFocusNode);
      if (_quantityFocusNode.hasFocus && !_quantityKeyboardVisible) {
        _hideKeyboard();
      }
    });
  }

  // 应用生命周期监听
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed && mounted) {
      _resetAllKeyboards();
    }
  }

  // 焦点变化处理
  void _handleFocusChange(String field, FocusNode node) {
    if (node.hasFocus) {
      if (_currentFocusField != null && _currentFocusField != field) {
        _hideKeyboardForField(_currentFocusField!);
      }
      _setCurrentFocusField(field);
    } else if (_currentFocusField == field) {
      _hideKeyboardForField(field);
      _currentFocusField = null;
    }
  }

  // 键盘控制方法
  void _setCurrentFocusField(String field) => setState(() => _currentFocusField = field);
  
  void _showKeyboard() async => await SystemChannels.textInput.invokeMethod('TextInput.show');
  
  Future<void> _hideKeyboard() async {
    try {
      await SystemChannels.textInput.invokeMethod('TextInput.hide');
      await Future.delayed(const Duration(milliseconds: 50));
      await SystemChannels.textInput.invokeMethod('TextInput.hide');
    } catch (e) {
      print('隐藏键盘失败: $e');
      await Future.delayed(const Duration(milliseconds: 100));
      await SystemChannels.textInput.invokeMethod('TextInput.hide');
    }
  }
  
  void _showKeyboardForField(String field) => setState(() {
    _updateKeyboardState(field, true);
    _showKeyboard();
  });
  
  void _hideKeyboardForField(String field) => setState(() {
    _updateKeyboardState(field, false);
    _hideKeyboard();
  });
  
  void _toggleKeyboardForField(String field) {
    if (_getKeyboardState(field)) {
      _hideKeyboardForField(field);
      _unfocusField(field);
    } else {
      _focusOnField(field, showKeyboard: true);
    }
  }
  
  // 聚焦方法（主方法）
  void _focusOnField(String field, {required bool showKeyboard}) {
    FocusScope.of(context).unfocus();
    if (mounted) {
      switch (field) {
        case 'location':
          FocusScope.of(context).requestFocus(_locationFocusNode);
          break;
        case 'item':
          FocusScope.of(context).requestFocus(_itemFocusNode);
          break;
        case 'quantity':
          FocusScope.of(context).requestFocus(_quantityFocusNode);
          break;
        case 'notes':
          FocusScope.of(context).requestFocus(_notesFocusNode);
          break;
      }
      if (showKeyboard) {
        _showKeyboardForField(field);
      } else {
        _hideKeyboard();
        // 关键修复：确保聚焦但不显示键盘时，图标状态正确
        _updateKeyboardState(field, false);
      }
    }
  }
  
  // 取消指定输入框焦点
  void _unfocusField(String field) {
    switch (field) {
      case 'location': _locationFocusNode.unfocus(); break;
      case 'item': _itemFocusNode.unfocus(); break;
      case 'quantity': _quantityFocusNode.unfocus(); break;
    }
  }
  
  // 获取键盘状态
  bool _getKeyboardState(String field) {
    switch (field) {
      case 'location': return _locationKeyboardVisible;
      case 'item': return _itemKeyboardVisible;
      case 'quantity': return _quantityKeyboardVisible;
      default: return false;
    }
  }
  
  // 更新键盘状态
  void _updateKeyboardState(String field, bool visible) {
    setState(() {
      switch (field) {
        case 'location': _locationKeyboardVisible = visible; break;
        case 'item': _itemKeyboardVisible = visible; break;
        case 'quantity': _quantityKeyboardVisible = visible; break;
      }
    });
  }
  
  // 重置所有键盘状态
  void _resetAllKeyboards() {
    if (_currentFocusField == null && !_locationKeyboardVisible && 
        !_itemKeyboardVisible && !_quantityKeyboardVisible) {
      return;
    }
    setState(() {
      _locationKeyboardVisible = false;
      _itemKeyboardVisible = false;
      _quantityKeyboardVisible = false;
      _currentFocusField = null;
    });
    FocusScope.of(context).unfocus();
    _hideKeyboard();
  }

  // 输入框点击处理
  void _onInputTap(TextEditingController controller, String fieldType) {
    if (controller.text.isNotEmpty) {
      controller.selection = TextSelection(
        baseOffset: 0,
        extentOffset: controller.text.length,
      );
    }
    // 关键修复：点击输入框时仅聚焦不自动显示键盘
    _focusOnField(fieldType, showKeyboard: false);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    
    // 移除焦点监听
    _locationFocusNode.removeListener(() => _handleFocusChange('location', _locationFocusNode));
    _itemFocusNode.removeListener(() => _handleFocusChange('item', _itemFocusNode));
    _quantityFocusNode.removeListener(() => _handleFocusChange('quantity', _quantityFocusNode));
    
    // 释放控制器资源
    _itemController.dispose();
    _locationController.dispose();
    _quantityController.dispose();
    _notesController.dispose();
    
    // 释放焦点资源
    _itemFocusNode.dispose();
    _locationFocusNode.dispose();
    _quantityFocusNode.dispose();
    _notesFocusNode.dispose();
    
    super.dispose();
  }

  // 清除错误提示
  void _clearErrorOnInput(String fieldKey){
    if (validationErrors.containsKey(fieldKey)) {
      setState(() {
        if (fieldKey == 'item' && _itemController.text.isNotEmpty) {
          validationErrors.remove(fieldKey);
        } else if (fieldKey == 'location' && _locationController.text.isNotEmpty) {
          validationErrors.remove(fieldKey);
        } else if (fieldKey == 'quantity' && _quantityController.text.isNotEmpty) {
          validationErrors.remove(fieldKey);
        } else if (fieldKey == 'adjustment' && _selectedAdjustmentType != null) {
          validationErrors.remove(fieldKey);
        }
      });
    }
  }

  // 扫描Location后跳转焦点，不弹键盘
  void _handleLocationBarcode(String value) async{
    try{
      if(value.isNotEmpty){
        if(value.contains(':')){
          setState(() {
            _locationController.text = Utils.parseQRCode(value, 'location');
          });
        }
        if(_itemController.text.isNotEmpty){
          final detail = await _fetchadjustmentDetail(warehouseId,_locationController.text.trim(),packKey,internalItemNumber);
          if(detail['code'] == 2000 && detail['data'].isNotEmpty){
            setState(() {
              currentQuantity = detail['data']['quantity'];
              if(_selectedAdjustmentType == 'Decrease'){
                maxAllowedValue = currentQuantity!;
              }
              else{
                maxAllowedValue = 9999999999999;
              }
            });
          }
        }
        _focusOnField('item', showKeyboard: false);
      }
    }catch(e){
      MessageBox.showMessageBox(context, e,isError: true);
    }
  }

  // 扫描Item后跳转焦点到Adjustment，不弹键盘
  void _handleItemBarcode(String value) async{
    try{
      if(!value.contains(':')){
        MessageBox.showMessageBox(context, 'Please scan item barcode.',isError: true);
      }
      if(value.isNotEmpty && value.contains(':')){
        packKey = Utils.parseQRCode(value, 'pack key');
        itemNumber = Utils.parseQRCode(value, 'item number');
        internalItemNumber = Utils.parseQRCode(value, 'product code');
        setState(() {
          _itemController.text = itemNumber;
        });
      }
      
      if(_locationController.text.isNotEmpty){
        final detail = await _fetchadjustmentDetail(warehouseId,_locationController.text.trim(),packKey,internalItemNumber);
        if(detail['code'] == 2000){
          setState(() {
            currentQuantity = detail['data']?['quantity'];
            _selectedAdjustmentType = 'Increase';
            maxAllowedValue = 999999999999999;
          });
          _focusOnField('adjustment', showKeyboard: false);
        }
      }
    }catch(e){
      MessageBox.showMessageBox(context, e,isError: true);
    }
  }

  // 获取详情数据
  Future<Map<String, dynamic>> _fetchadjustmentDetail(int? warehouseId,String location,String? packKey,String? internalItemNumber) async {
    final warehouseIdParam = 'warehouse=$warehouseId';
    final locationParam = '&location=${_locationController.text.trim()}';
    final packKeyParam = '&pack_key=$packKey';
    final internalItemNumberParam = '&&internal_item_number=$internalItemNumber';
    final apiUrl = '${ApiService.baseURL}${ApiService.adjuestmentDetail}$warehouseIdParam$locationParam$packKeyParam$internalItemNumberParam';

    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;

    if (accessToken == null) {
      throw 'The session has expired, Please log in again.';
    }
    
    try {
      final response = await http.get(
        Uri.parse(apiUrl),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'X-Client-Type':'app'
        },
      ).timeout(const Duration(seconds: 10));
      
      if (response.statusCode == 200) {
        String responseBody = utf8.decode(response.bodyBytes);
        Map<String, dynamic> jsonData = json.decode(responseBody);
        if (jsonData['code'] == 2000 && jsonData['data'] != null && jsonData['data'] != '') {
          return jsonData;
        }
        else if (jsonData['code'] == 401) {
          AuthService auth = AuthService();
          auth.logout(context);
          throw 'The session has expired, Please log in again.';
        }
        else {
          throw jsonData['msg'];
        }
      }
      else {
        throw response.statusCode;
      }
    } catch (e) {
      throw e;
    }
  }

  // 验证输入并提交
  void _submitForm() {
    _resetAllKeyboards();
    bool isValid = true;
    Map<String, String?> errors = {};

    // 验证Item
    if (_itemController.text.isEmpty) {
      errors['item'] = 'Please input item number.';
      isValid = false;
    }

    // 验证Location
    if (_locationController.text.isEmpty) {
      errors['location'] = 'Please input location.';
      isValid = false;
    }

    // 验证Adjustment Type
    if (_selectedAdjustmentType == null) {
      errors['adjustment'] = 'Please choose adjustment type.';
      isValid = false;
    }

    // 验证Quantity
    if (_quantityController.text.isEmpty) {
      errors['quantity'] = 'Please input quantity.';
      isValid = false;
    } else if (int.tryParse(_quantityController.text) == null) {
      errors['quantity'] = 'Invalid number.';
      isValid = false;
    }

    // 更新错误状态
    setState(() {
      validationErrors = errors;
    });

    // 如果验证通过，调用API
    if (isValid) {
      _callAdjustmentAPI();
    }
    _notesFocusNode.unfocus();
  }

  // 提交成功后重新聚焦Location，不弹键盘
  void _callAdjustmentAPI() async{
    try{
      final detail = await _adjustment();
      if(detail['code'] == 2000){
        await showDialog(
          context: context,
          barrierDismissible: false,
          builder: (BuildContext context) {
            final screenWidth = MediaQuery.of(context).size.width;
            
            return AlertDialog(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8.0),
              ),
              contentPadding: const EdgeInsets.fromLTRB(20, 15, 20, 10),
              titlePadding: const EdgeInsets.fromLTRB(20, 15, 20, 10),
              actionsPadding: const EdgeInsets.fromLTRB(20, 5, 20, 15),
              
              title: Text(
                'Success',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 16 * _fontScale,
                  color:  const Color.fromARGB(255, 4, 170, 10)
                ),
              ),
              content: SingleChildScrollView(
                child: ConstrainedBox(
                  constraints: BoxConstraints(
                    maxWidth: screenWidth * 0.6,
                  ),
                  child: ListBody(
                    children: <Widget>[
                      Text(
                        detail['msg'],
                        style: TextStyle(fontSize: 14 * _fontScale),
                      ),
                    ],
                  ),
                ),
              ),
              actions: <Widget>[
                TextButton(
                  child: Text(
                    'OK',
                    style: TextStyle(
                      fontSize: 14 * _fontScale,
                      color: const Color(0xFF008363),
                    ),
                  ),
                  onPressed: () {
                    Navigator.of(context).pop();
                    if (mounted) {
                      _focusOnField('location', showKeyboard: false);
                    }
                  },
                ),
              ],
            );
          },
        );
        setState((){
          packKey = null;
          internalItemNumber = null;
          _locationController.clear();
          _itemController.clear();
          _selectedAdjustmentType = 'Increase';
          currentQuantity = 0;
          maxAllowedValue = 999999999999999;
          _quantityController.clear();
          _notesController.clear();
        });
      }
    }catch(e){
      MessageBox.showMessageBox(context, e,isError: true);
    }
  } 

  // 调用调整API（传递选中的调整类型）
  Future<Map<dynamic,dynamic>> _adjustment() async {
    final apiUrl = ApiService.baseURL + ApiService.updateAdjuestmentDetail;
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;
    var adjustmentType = '';
    if(_selectedAdjustmentType == 'Set'){
      adjustmentType = 'Set Quantity';
    }
    else if(_selectedAdjustmentType == 'Increase'){
      adjustmentType = 'Increase Quantity';
    }
    else{
      adjustmentType = 'Decrease Quantity';
    }
    
    try {
      
      var requestBody = {
        'warehouse': warehouseId,
        'location': _locationController.text.trim(),
        'internal_item_number': internalItemNumber,
        'pack_key': packKey,
        'adjustment_quantity': int.parse(_quantityController.text.trim()),
        'adjustment': adjustmentType.isNotEmpty?adjustmentType:'Increase Quantity',
        'notes': _notesController.text.toString(),
      };
      final response = await http.post(
        Uri.parse(apiUrl),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type':'application/json',
          'X-Client-Type':'app'
        },
        body: jsonEncode(requestBody),
      );
      
      if(response.statusCode == 200){
        String responseBody = utf8.decode(response.bodyBytes);
        Map<String, dynamic> jsonData = json.decode(responseBody);
        if (jsonData['code'] == 2000) {
          return jsonData;
        }
        else if(jsonData['code'] == 401){
          AuthService auth = AuthService();
          auth.logout(context);
          throw Exception('The session has expired, Please log in again.');
        }
        else {
          throw Exception('${jsonData['msg']}');
        }
      }
      else{
        throw Exception('${response.statusCode}');
      }
    } catch (e) {
      throw Exception('$e');
    }
  }

  // 构建标签+输入框的行布局
  Widget _buildLabelInputRow({
    required String label,
    required Widget child,
    bool isRequired = false,
    String? errorKey,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(
          height: 30,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              // 标签部分
              SizedBox(
                width: 120,
                child: Row(
                  children: [
                    Text(
                      label,
                      style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13 * _fontScale),
                    ),
                    if (isRequired)
                      const Text(
                        '*',
                        style: TextStyle(color: Colors.red),
                      ),
                  ],
                ),
              ),
              const SizedBox(width: 16),
              // 输入框部分
              Expanded(child: child),
            ],
          ),
        ),
        // 错误提示
        if (errorKey != null && validationErrors[errorKey] != null)
          Padding(
            padding: const EdgeInsets.only(left: 136, top: 4),
            child: Text(
              validationErrors[errorKey]!,
              style: TextStyle(
                color: Colors.red,
                fontSize: 12 * _fontScale,
              ),
            ),
          ),
      ],
    );
  }

  // 带键盘图标的输入框
  Widget _buildKeyboardInputField({
    required String fieldType,
    required TextEditingController controller,
    required FocusNode focusNode,
    TextInputType keyboardType = TextInputType.text,
    List<TextInputFormatter>? inputFormatters,
    Function(String)? onSubmitted,
    Function(String)? onChanged,
  }) {
    final isSmallScreen = MediaQuery.of(context).size.width < 360;
    
    return TextField(
      controller: controller,
      focusNode: focusNode,
      keyboardType: keyboardType,
      inputFormatters: inputFormatters,
      decoration: InputDecoration(
        border: const OutlineInputBorder(),
        contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 10),
        suffixIcon: IconButton(
          icon: Icon(
            // 关键修复：根据实际键盘状态显示正确图标
            _getKeyboardState(fieldType) ? Icons.keyboard_hide : Icons.keyboard,
            color: const Color(0xFF008363),
            size: isSmallScreen ? 18 : 20,
          ),
          onPressed: () => _toggleKeyboardForField(fieldType),
          splashRadius: 20,
          padding: const EdgeInsets.all(4),
          constraints: const BoxConstraints.tightFor(width: 36, height: 36),
        ),
      ),
      style: TextStyle(fontSize: 13 * _fontScale),
      onSubmitted: onSubmitted,
      onTap: () => _onInputTap(controller, fieldType),
      onChanged: onChanged,
      onTapOutside: (event) {
        // 关键修复：点击外部时更新键盘状态
        _hideKeyboardForField(fieldType);
        _unfocusField(fieldType);
      },
    );
  }

  // 构建调整类型的按钮（核心修改：极致缩小，字体贴近边缘）
  Widget _buildAdjustmentButton(String type, bool isSmallScreen) {
    final isSelected = _selectedAdjustmentType == type;
    // 极致缩小参数：最小化高度、内边距、字体
    final buttonHeight = isSmallScreen ? 18.0 : 22.0; // 移动端18px（极限高度，确保文字不截断）
    final buttonFontSize = isSmallScreen ? 12 * _fontScale : 13 * _fontScale; // 最小可读字体
    final buttonPadding = EdgeInsets.only(left: 5,right: 5); // 完全移除内边距，字体贴边缘
    
    return ElevatedButton(
      style: ElevatedButton.styleFrom(
        backgroundColor: isSelected ? const Color(0xFF008363) : const Color.fromARGB(255, 233, 232, 232),
        foregroundColor: isSelected ? Colors.white : Colors.black,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(2), // 极小圆角，视觉更紧凑
          side: BorderSide.none, // 移除边框（若有）
        ),
        // 关键修复：固定高度，宽度随文字自适应（原错误用了fromWidth）
        fixedSize: Size.fromRadius(25),
        // 完全移除内边距，让字体贴近按钮边缘
        padding: buttonPadding,
        // 限制最小尺寸，避免按钮因内容过少而过大
        minimumSize: Size.zero,
        // 移除所有阴影，视觉上最小化
        elevation: 0,
        shadowColor: Colors.transparent,
      ),
      onPressed: () {
        setState(() {
          _selectedAdjustmentType = type;
          if (type == 'Set') {
            maxAllowedValue = 999999999999999;
            quantityOnly = true;
          } else {
            quantityOnly = false;
            if (type == 'Increase' && _quantityController.text.isNotEmpty) {
              maxAllowedValue = 999999999999999;
            } else if (type == 'Decrease' && _quantityController.text.isNotEmpty) {
              maxAllowedValue = currentQuantity ?? 0;
              if (int.tryParse(_quantityController.text) != null && currentQuantity != null && int.parse(_quantityController.text) > currentQuantity!) {
                _quantityController.text = currentQuantity.toString();
              }
            }
          }
          _clearErrorOnInput('adjustment');
        });
      },
      child: Text(
        type,
        style: TextStyle(
          fontSize: buttonFontSize,
          height: 1.0, // 行高1.0，完全贴合垂直方向
          letterSpacing: -0.2, // 轻微缩小字间距，进一步紧凑
        ),
        overflow: TextOverflow.visible, // 确保文字不被截断
        softWrap: false, // 禁止换行，保持单行
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    _fontScale = Provider.of<FontSizeProvider>(context).fontScale;
    final user = Provider.of<AuthService>(context).currentUser;
    warehouseId = user?.warehouse;
    final isSmallScreen = MediaQuery.of(context).size.width < 360; // 小屏幕判断（<360px）

    return Scaffold(
      appBar: AppBar(
        title: Text('Adjustment', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18 * _fontScale)),
        automaticallyImplyLeading: false,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () {
            _resetAllKeyboards();
            Navigator.pushNamed(context,'/inventory');
          },
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.home, color: Colors.white),
            onPressed: () {
              _resetAllKeyboards();
              Navigator.pushNamed(context, '/home');
            },
          ),
        ],
        backgroundColor: const Color(0xFF008363),
      ),
      resizeToAvoidBottomInset: false,
      body: Stack(
        children: [
          // 可滚动内容区
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            bottom: _bottomButtonHeight,
            child: GestureDetector(
              onTap: _resetAllKeyboards,
              behavior: HitTestBehavior.translucent,
              child: SingleChildScrollView(
                padding: EdgeInsets.all(isSmallScreen ? 16 : 32),
                child: Column(
                  children: [
                    // Location 输入框（带键盘图标）
                    _buildLabelInputRow(
                      label: 'Location:',
                      isRequired: true,
                      errorKey: 'location',
                      child: _buildKeyboardInputField(
                        fieldType: 'location',
                        controller: _locationController,
                        focusNode: _locationFocusNode,
                        onSubmitted: _handleLocationBarcode,
                        onChanged: (value) => _clearErrorOnInput('location'),
                      ),
                    ),
                    const SizedBox(height: 20),
                    
                    // Item 输入框（带键盘图标）
                    _buildLabelInputRow(
                      label: 'Item:',
                      isRequired: true,
                      errorKey: 'item',
                      child: _buildKeyboardInputField(
                        fieldType: 'item',
                        controller: _itemController,
                        focusNode: _itemFocusNode,
                        onSubmitted: _handleItemBarcode,
                        onChanged: (value) => _clearErrorOnInput('item'),
                      ),
                    ),
                    const SizedBox(height: 20),
                    
                    // 当前数量显示
                    _buildLabelInputRow(
                      label: 'Current Quantity:',
                      child: Container(
                        padding: const EdgeInsets.symmetric(vertical: 0, horizontal: 10),
                        height: 30,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Align(
                          alignment: Alignment.centerLeft,
                          child: Text(
                            currentQuantity != null?'$currentQuantity':'',
                            style: TextStyle(fontSize: 13 * _fontScale, fontWeight: FontWeight.w500),
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(height: 20),
                    
                    // 调整类型：三个并列按钮（极致紧凑布局）
                    _buildLabelInputRow(
                      label: 'Adjustment:',
                      isRequired: true,
                      errorKey: 'adjustment',
                      child: Padding(
                        // 完全移除外层留白
                        padding: EdgeInsets.zero,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween, // 均匀分配空间
                          crossAxisAlignment: CrossAxisAlignment.center, // 垂直居中对齐
                          children: [
                            _buildAdjustmentButton('Increase', isSmallScreen),
                            // 按钮之间极限小间距（1px）
                            SizedBox(width: 1),
                            _buildAdjustmentButton('Decrease', isSmallScreen),
                            SizedBox(width: 1),
                            _buildAdjustmentButton('Set', isSmallScreen),
                          ],
                        ),
                      ),
                    ),
                    const SizedBox(height: 20),
                    
                    // 数量输入（带键盘图标）
                    _buildLabelInputRow(
                      label: 'Quantity:',
                      isRequired: true,
                      errorKey: 'quantity',
                      child: _buildKeyboardInputField(
                        fieldType: 'quantity',
                        controller: _quantityController,
                        focusNode: _quantityFocusNode,
                        keyboardType: TextInputType.number,
                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly,
                          RangeInputFormatter(maxAllowedValue)
                        ],
                        onSubmitted: (_) => _focusOnField('notes', showKeyboard: false),
                        onChanged: (value) => _clearErrorOnInput('quantity'),
                      ),
                    ),
                    const SizedBox(height: 20),
                    
                    // 备注
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(
                          width: 120,
                          child: Padding(
                            padding: const EdgeInsets.only(top: 8),
                            child: Text(
                              'Notes:',
                              style: TextStyle(
                                fontWeight: FontWeight.bold, 
                                fontSize: 13 * _fontScale,
                              ),
                            ),
                          ),
                        ),
                        const SizedBox(width: 16),
                        Expanded(
                          child: TextField(
                            focusNode: _notesFocusNode,
                            controller: _notesController,
                            maxLines: 6,
                            decoration: const InputDecoration(
                              hintText: 'Note...',
                              border: OutlineInputBorder(),
                              contentPadding: EdgeInsets.all(10),
                            ),
                            style: TextStyle(fontSize: 13 * _fontScale),
                            onTap: _resetAllKeyboards,
                            onTapOutside: (event) => _notesFocusNode.unfocus(),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 20),
                  ],
                ),
              ),
            ),
          ),
          
          // 底部提交按钮区
          Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            child: Container(
              padding: const EdgeInsets.all(24),
              width: double.infinity,
              color: Theme.of(context).scaffoldBackgroundColor,
              child: ElevatedButton(
                onPressed: _submitForm,
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF008363),
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                ),
                child: Text(
                  'Submit',
                  style: TextStyle(fontSize: 16 * _fontScale, fontWeight: FontWeight.bold, color: Colors.white),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}